package qs.openxt.libs.plugins;

import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * 获取GPS
 *
 * @author 颖杰_2
 */
public class QTBdGpsPlugins extends CordovaPlugin {
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    private CallbackContext callbackContext;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    callbackContext.success((String) msg.obj);
                    break;
                }
                case 2: {
                    Toast.makeText(cordova.getActivity(), (String) msg.obj, Toast.LENGTH_LONG).show();
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    private void sendMessage(int what, String mMessage){
        Message msg = new Message();
        msg.what = what;
        msg.obj = mMessage;
        mHandler.sendMessage(msg);
    }

    private void initLocation(){
        mLocationClient = new LocationClient(cordova.getActivity().getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener( myListener );

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        option.setScanSpan(2000);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        //option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        //option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        //option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        //option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
        this.callbackContext = callbackContext;
        if ("doBdGpsApp".equals(action)) {
            try {
                initLocation();
                mLocationClient.start();
            }catch (Exception e) {
            }
            return true;
        }
        return false;
    }

    class MyLocationListener implements BDLocationListener {
        int index = 0;
        @Override
        public void onReceiveLocation(BDLocation location) {
            if(location == null)
                return;
            if(index > 2){
                index = 0;
                int locType = location.getLocType();
                if(BDLocation.TypeCriteriaException == locType){
                    sendMessage(2, "网络不同导致定位失败，请检查网络是否通畅");
                    return;
                }else if(BDLocation.TypeNetWorkException == locType){
                    sendMessage(2, "无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                    return;
                }else if(BDLocation.TypeServerError == locType){
                    sendMessage(2, "网络不同导致定位失败，请检查网络是否通畅");
                    return;
                }

                if(BDLocation.TypeGpsLocation == locType || BDLocation.TypeOffLineLocation == locType || BDLocation.TypeNetWorkLocation == locType) {
                    mLocationClient.unRegisterLocationListener(myListener); //注销掉监听
                    mLocationClient.stop(); //停止定位服务

                    //纬度
                    double latitude = location.getLatitude();
                    //经度
                    double longitude = location.getLongitude();

                    try {
                        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
                        json.put("longitude", longitude);
                        json.put("latitude", latitude);

                        sendMessage(1, json.toString());
                    }catch (Exception e){
                    }
                }
            }
            index++;
        }
    }
}
